//获取mongodb
const { contentModel } = require("../mongodb");
const { success, fail } = require("../toast");

module.exports = function (router) {

    //查询
    router.get("/content", async ctx => {
        try {
            const data = await contentModel.find(ctx.query);
            return success(ctx, data);
        } catch (error) {
            return fail(ctx, error);
        }
        // ctx.body="content";
    })
    //动态路由 查询单个
    router.get("/content/:id",async ctx=>{
        try {
            const data = await contentModel.findOne({_id:ctx.params.id});
            return success(ctx, data);
        } catch (error) {
            return fail(ctx, error);
        }
    })


    //添加
    router.post("/content", async ctx => {
        try {
            const data = await contentModel.create(ctx.request.body);
            return success(ctx, data);
        } catch (error) {
            return fail(ctx, error);
        }
        // ctx.body="content";
    })


    //删除
    router.delete("/content", async ctx => {
        try {
            const _id=ctx.request.body._id;
            let data=[];
            if(_id instanceof Array){
                // console.log("数组");
                data=await contentModel.deleteMany({_id:{$in:_id}});
            }else{
                // console.log("非数组");
                data=await contentModel.deleteMany({_id:_id});
            }
            // const data = await contentModel.deleteMany(ctx.request.body);
            // const data=[];
            success(ctx, data);
        } catch (error) {
            return fail(ctx, error);
        }
        // ctx.body="content";
    })


    //修改
    router.put("/content/:id", async ctx => {
        try {
            const data = await contentModel.updateOne({_id:ctx.params.id}, ctx.request.body);
            return success(ctx, data);
        } catch (error) {
            return fail(ctx, error);
        }
        // ctx.body="content";
    })
}

/*
    {
        status:200,
        data:[]/{},
        msg:""
    }
*/